package com.zemb.flxwear.TaskQueue;


import com.zemb.flxwear.Bean.ReportItem;
import com.zemb.flxwear.Utils.DeviceUtils;

import java.util.ArrayList;
import java.util.List;

//定义叫做TaskQueue的队列
public class TaskQueue {
    private List<BaseTask> queue;
    //当前任务下标
    private int currentTaskIndex = 0;

    private OnTaskFinishedListener listener;

    //构造函数
    public TaskQueue() {
        this.queue = new ArrayList<>();
    }

    //添加任务
    public void addTask(BaseTask task) {
        queue.add(task);
    }

    //完成任务
    public void finishTask(ReportItem item) {
        try {
            queue.get(currentTaskIndex).setFinished(true);
            queue.get(currentTaskIndex).setSuccess(true);
            queue.get(currentTaskIndex).setResult(item);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void failTask(DeviceUtils.Category category) {
        try {
            queue.get(currentTaskIndex).setFinished(true);
            queue.get(currentTaskIndex).setSuccess(false);
            queue.add(new BaseTask(category));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    public void passTask(){
        try {
            queue.get(currentTaskIndex).setFinished(true);
            queue.get(currentTaskIndex).setSuccess(false);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void next() {
        currentTaskIndex++;
    }

    //获取当前任务
    public BaseTask getCurrentTask() {
        try {
            if (currentTaskIndex >= queue.size()) {
                return null;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return queue.get(currentTaskIndex);
    }


    //清空队列
    public void clear() {
        queue.clear();
    }

    public interface OnTaskFinishedListener {
        void onTaskFinished();

        void onTaskFailed();

        void onTaskProgress(int progress);

        void onAllFailed();

        void onTaskStart(BaseTask task);
    }

    public List<ReportItem> getAllResult() {
        List<ReportItem> list = new ArrayList<>();

        try {
            for (BaseTask task : queue) {
                if (task.getResult() != null) {
                    list.add(task.getResult());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }
}


